package com.hxd.Login.LoginService;

import com.hxd.Login.LoginDao.loginDao;
import com.hxd.pojo.User;
import com.hxd.util.MailUtil;
import com.hxd.util.VerifyCodeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Service

public class loginServiceImpl implements loginService {
    @Resource
    loginDao loginDao;

    //登录验证信息
    @Override
    public Boolean verify(User user, HttpSession session) {
        //根据id(账号)查询用户
        User user1 = loginDao.verify(user);
        if (user1 != null && user.getUser_password().equals(user1.getUser_password())){
            session.setAttribute("user",user1);
            return true;
        }
        return false;
    }

    //根据用户名查询出来信息自动填充姓名邮箱
    @Override
    public User verification(User user) {
        if(user != null){
            //根据id(账号)查询用户
            User user1 = loginDao.verify(user);
            return user1;
        }
        return null;
    }

    //获取邮件验证码
    @Override
    @Transactional
    public int verifeCode(User user) throws MessagingException {
        if(user != null) {
            User user1 = loginDao.verify(user);
            int verificationCode = (int) ((Math.random() * 9 + 1) * 100000);
            //email用户填写的电子邮件    emailCode验证码
            MailUtil.sendMail(user1.getUser_email(), verificationCode);
            return verificationCode;
        }
        return 0;
    }

    //发送验证码,修改密码
    @Override
    @Transactional
    public void modifyUserPassword(User user) {
        loginDao.modifyUserPassword(user);
    }

    //生成登录验证码
    @Override
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = VerifyCodeUtils.getSecurityCode();
        //将验证码放入session
        session.setAttribute("code", securityCode);
        System.out.println("===登录验证码===" + securityCode + "========");
        //生成图片
        BufferedImage image = VerifyCodeUtils.createImage(securityCode);
        //输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        //调用工具类
        ImageIO.write(image, "png", outputStream);
    }
}